package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.Topo;
import com.ruoyi.system.domain.TopoEdge;
import com.ruoyi.system.domain.TopoNode;
import com.ruoyi.system.domain.vo.TopoVO;
import com.ruoyi.system.mapper.TopoEdgeMapper;
import com.ruoyi.system.mapper.TopoMapper;
import com.ruoyi.system.mapper.TopoNodeMapper;
import com.ruoyi.system.service.ITopoEdgeService;
import com.ruoyi.system.service.ITopoNodeService;
import com.ruoyi.system.service.ITopoService;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TopoSerivceImpl implements ITopoService {
    @Autowired
    private TopoMapper topoMapper;
    @Autowired
    private TopoEdgeMapper topoEdgeMapper;
    @Autowired
    private TopoNodeMapper topoNodeMapper;

    @Autowired
    private ITopoEdgeService topoEdgeService;
    @Autowired
    private ITopoNodeService topoNodeService;

    @Override
    public List<Topo> selectAll() {
        return topoMapper.selectALl();
    }

    @Override
    public TopoVO selectById(Long topoId) {
        Topo topo = topoMapper.selectById(topoId);
        List<TopoEdge> topoEdges = topoEdgeMapper.selectByTopoId(topoId);
        List<TopoNode> topoNodes = topoNodeMapper.selectByTopoId(topoId);
        TopoVO topoVO = new TopoVO();
        topoVO.setTopoId(topo.getTopoId());
        topoVO.setTopoName(topo.getTopoName());
        topoVO.setEdges(topoEdges);
        topoVO.setNodes(topoNodes);
        return topoVO;
    }

    @Override
    public void addTopo(TopoVO topoVO) {
        //先查询看有没有已经存在的这个topo 如果有 就修改 如果没有 就新增
        Topo topo = topoMapper.selectById(topoVO.getTopoId());
        if (topo != null) {
            //不为空 说明要修改
            topo.setTopoName(topoVO.getTopoName());
            topoMapper.updateTopo(topo);
        } else {
            //如果查出来为空的话 说明需要新增进去
            Topo topoEntity = new Topo();
            topoEntity.setTopoName(topoVO.getTopoName());
            topoMapper.addTopo(topoEntity);
            //获取新增完的topoid
            topoVO.setTopoId(topoEntity.getTopoId());
        }

        //新增拓扑下的节点
        topoNodeService.addTopoNode(topoVO);

        //新增拓扑下的边
        topoEdgeService.addTopoEdge(topoVO);
    }

    @Override
    public Boolean deleteTopo(Long topoId) {
        Topo topo = topoMapper.selectById(topoId);
        if (topo != null) {
            //既要删除topo表里的数据，还要删除topo_node和topo_edge表里对应的topoId的数据
            topoMapper.deleteTopo(topoId);
            topoEdgeMapper.deleteByTopoId(topoId);
            topoNodeMapper.deleteByTopoId(topoId);
        }
        return true;
    }
}
